package com.zh.kotlin_mvvm.ui

import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.zh.common.base.BaseActivity
import com.zh.common.base.BaseMapToBody
import com.zh.common.ktx.fromJsonObj
import com.zh.common.ktx.liveObserve
import com.zh.common.ktx.liveObserveSticky
import com.zh.common.ktx.liveSetValue
import com.zh.common.ktx.toast
import com.zh.common.net.requestApi
import com.zh.common.utils.EmptyUtils
import com.zh.common.utils.toast.ZToastUtils
import com.zh.config.ZjConfig
import com.zh.kotlin_mvvm.bean.ChatBean
import com.zh.kotlin_mvvm.bean.ChatBody
import com.zh.kotlin_mvvm.bean.ChatList
import com.zh.kotlin_mvvm.bean.TokenBean
import com.zh.kotlin_mvvm.databinding.ActivityTextMainBinding
import com.zh.kotlin_mvvm.net.netService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.apache.commons.net.ftp.FTPClient
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.*


@Route(path = ZjConfig.TextNetActivity)
class TextNetActivity : BaseActivity<ActivityTextMainBinding>() {

    val myObservable = MyObservable()
    val myObserver = MyObserver()
    var access_token: String? = null

    override fun initView(savedInstanceState: Bundle?) {
        liveObserveSticky<String>("name") {
            ZToastUtils.showShort(it)
        }
        myObservable.addObserver(myObserver)

        println((0..6).map {
            it + 2
        }.filter {
            it % 2 == 0
        })//[2, 4, 6, 8]
        println((0..6).map {
            it + 2
        }.takeWhile {
            it % 2 == 0
        })//[2]

        liveObserve<String>("data") {
            if (it.contains("access_token")) {
                "access_token获取成功".toast()
                val bean = fromJsonObj(it, TokenBean::class.java)
                bean?.let { access_token = it.access_token }
            } else if (it.contains("result")) {
                val bean = fromJsonObj(it, ChatBean::class.java)
                viewBinding.tvContent.text = bean?.result
            }
        }
    }

    fun token(view: View) {
        //文心一言，千帆大模型接口
        val grantType = "client_credentials"
        val clientKey = "9Avpuui2K1QNbsciaIpOSzvM"
        val clientSecret = "0W31bWdOK1vzbl3Km1ygmGOutga2Vj3n"
        requestApi({
            netService("https://aip.baidubce.com/")
                .token("application/json", grantType, clientKey, clientSecret)
        }, true)
    }

    fun doChat(view: View) {
        if (access_token == null) {
            "先获取access_token".toast()
            return
        }
        val content = viewBinding.etContent.text.toString()
        if (EmptyUtils.isEmpty(content)) {
            "请输入内容".toast()
            return
        }
        val list = mutableListOf<ChatList>()
        list.add(ChatList("user", content))
        requestApi({
            netService("https://aip.baidubce.com/")
                .chat("application/json", access_token!!, ChatBody(list))
        }, true)
    }

    fun netLogin(view: View) {
        viewBinding.sid2.text = "开始请求"
        val map = mapOf<String, Any>(
            "mobile" to "13648394964",
            "pwd" to "123456",
            "loginType" to "PASSWORD"
        )
        doLogin(map)
        liveSetValue("change", "你变了吗？")
    }

    fun netLogin2(view: View) {
        val map = mapOf<String, Any>(
            "mobile" to "13648394964",
            "pwd" to "123456",
            "loginType" to "PASSWORD"
        )
        doLogin2(map)
    }

    fun doLogin(map: Map<String, Any>) {
        requestApi({ netService().login(BaseMapToBody.convertMapToBody(map)) }, true,
            error = { code, msg ->
                viewBinding.sid.text = msg
                "code=${code}".toast()
            }) {
            viewBinding.sid.text = it?.bussData
            "code=${it?.resultCode}".toast()
        }
    }

    fun doLogin2(map: Map<String, Any>) {
        val host = "https://api.apiopen.top"
        requestApi({ netService(host).getSingleJoke("28654780") }, true, error = { code, msg ->
            viewBinding.sid.text = msg
            "code=${code}".toast()
        }) {
            viewBinding.sid.text = it?.comment
            "code=${it?.name}".toast()
        }
    }

    fun netLogin3(view: View) {
        myObservable.speak("大宝贝")
    }

    fun netFtp(view: View) {
        val path = "ftp://a.gbl.114s.com:20320/0325/雄兵连04.mp4"
        val etString = viewBinding.etFtp.text.toString().trim()
        val serverAddress = etString.ifEmpty { path }
        val localFolderPath = "$filesDir${File.separator}ftp"
        lifecycleScope.launch(Dispatchers.IO) {
            val ftpClient = FTPClient()
            try {
                val uri = Uri.parse(serverAddress)
                ftpClient.connect(uri.host, uri.port)
                ftpClient.login("user", "")
                ftpClient.enterLocalPassiveMode()
                ftpClient.changeWorkingDirectory(uri.pathSegments[0])
                val localFolder = File(localFolderPath)
                if (!localFolder.exists()) {
                    localFolder.mkdirs()
                }
                val localFile = File(localFolderPath, uri.lastPathSegment)
                val outputStream = BufferedOutputStream(FileOutputStream(localFile))
                val success = ftpClient.retrieveFile(uri.lastPathSegment, outputStream)
                outputStream.close()
                if (success) {
                    // 文件下载成功
                    toast("下载成功")
                } else {
                    toast("下载失败")
                }
            } catch (e: IOException) {
                e.printStackTrace()
                toast(e.message)
            } finally {
                try {
                    if (ftpClient.isConnected) {
                        ftpClient.logout()
                        ftpClient.disconnect()
                    }
                } catch (ex: IOException) {
                    ex.printStackTrace()
                }
            }
        }
//        XGUtil.getPlayUrl(serverAddress, object : XGUtil.GetVlcVideoBean {
//            override fun getVlcVideoBean(vlcVideoBean: VlcVideoBean?) {
//                LogUtils.e(vlcVideoBean?.videoHttpUrl, vlcVideoBean?.videoPlayUrl)
//            }
//        })
    }

    override fun onDestroy() {
        myObservable.deleteObserver(myObserver)
        super.onDestroy()
    }
}

//设置需要改变的数据
class MyObservable : Observable() {//被观察着

    fun speak(name: String?) {
        setChanged()
        notifyObservers(name)
    }
}

//接收改变的数据，并在这里实现逻辑
class MyObserver : Observer {
    //观察着
    override fun update(o: Observable?, arg: Any?) {
        arg.toast()
    }
}